/*
 *  Copyright (C) 2020 original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License. You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software distributed under the License
 *  is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 *  or implied. See the License for the specific language governing permissions and limitations under
 *  the License.
 */

package vip.justlive.easyproxy.core.context;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * 数据统计
 *
 * @author wubo
 */
@Data
@Accessors(chain = true)
public class Metrics implements Serializable {

  private static final long serialVersionUID = -8541044218025622918L;
  private static final Map<Integer, Metrics> METRICS = new ConcurrentHashMap<>(4);

  private final int port;
  private final long createAt = System.currentTimeMillis();

  private AtomicLong readBytes = new AtomicLong();
  private AtomicLong writeBytes = new AtomicLong();
  private AtomicInteger serverChannels = new AtomicInteger();
  private AtomicInteger clientChannels = new AtomicInteger(-1);

  public static Metrics metrics(int port) {
    return METRICS.computeIfAbsent(port, Metrics::new);
  }

  public static Collection<Metrics> metrics() {
    return METRICS.values();
  }
}
